<?php
namespace Manage\Model;
use Think\Model;
class BannerModel extends Model{
	private $DescriptionModel;
	function _initialize(){
		parent::_initialize();
		$this->DescriptionModel=M('BannerImageDescription');
	}
	/**
	 * 操作
	 */
	public function operBanner($data,$banner_id=0){
		$banner_data=$this->create($data);
		$banner_data['date_modified']=time();

		if($banner_id){
			$map['banner_id']=$banner_id;
			$this->data($banner_data)->where($map)->save();
		}else{
			$banner_data['date_added']=time();
			$banner_id=$this->add($banner_data);
		}

		$ImageModel=M('BannerImage');
		$ImageModel->where(array('banner_id'=>$banner_id))->delete();
		if($data['banner_image']){
			foreach ($data['banner_image'] as $image) {
				$image_data=$ImageModel->create($image);
				$image_data['banner_id']=$banner_id;
				$banner_image_id=$ImageModel->add($image_data);
				if($banner_image_id){
					foreach ($image['banner_image_description'] as $language_id => $bid) {
						$bid['language_id']=$language_id;
						$bid['banner_image_id']=$banner_image_id;
						$this->DescriptionModel->add($bid);
					}
				}
			}
		}
	}

	public function getBanners($data){
		$page=array(
			'start'		=>	$data['start'],
			'limit'		=>	$data['limit']
			);
		$order	=	'sort_order ' . (isset($data['order'])?$data['order']:'ASC');
		$order .= ',banner_id DESC';
		$list=$this->order($order)->limit($page['start'],$page['limit'])->select();
		return $list;
	}

	public function getCount($data=array()){
		return $this->count();
	}

	public function getBanner($banner_id=0){
		
		$map['banner_id']=$banner_id;
		$banner=$this->where($map)->find();

		$ImageModel=M('BannerImage');
		
		$banner_image=$ImageModel->where($map)->order('sort_order ASC,banner_image_id DESC')->select();
		foreach ($banner_image as $key=> $image) {
			$banner_image[$key]['banner_image_description']=$this->getBannerImageDescription($image['banner_image_id']);
		}
		if(!empty($banner_image)) $banner['banner_image']=$banner_image;
		return $banner;

	}

	private function getBannerImageDescription($banner_image_id){
		$return=array();
		$map['banner_image_id']=$banner_image_id;
		$bid=$this->DescriptionModel->where($map)->select();
		foreach ($bid as $v) {
			$return[$v['language_id']]=$v;
		}
		return $return;
	}

	public function del($banner_id){
		$ImageModel=M('BannerImage');
		$map['banner_id']=$banner_id;
		$banner_image=$ImageModel->where($map)->select();
		foreach ($banner_image as $v) {
			$this->DescriptionModel->where(array('banner_image_id'=>$v['banner_image_id']))->delete();
		}
		$ImageModel->where($map)->delete();
		return $this->where($map)->delete();
	}
}